package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import com.example.qu_tao.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DingDanActivity extends AppCompatActivity implements View.OnClickListener {
    private GridView gridView;
    private LinearLayout emptyLayout;
    private List<Map<String, Object>> dataList;
    private SimpleAdapter adapter;
    private BroadcastReceiver orderUpdateReceiver;


    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dingdanguanli);

        initView();
        loadCollectionData();

        // 注册广播接收器
        orderUpdateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (GoodsDetailActivity.ACTION_ORDER_UPDATED.equals(intent.getAction())) {
                    loadCollectionData();
                }
            }
        };
        IntentFilter filter = new IntentFilter(GoodsDetailActivity.ACTION_ORDER_UPDATED);
        registerReceiver(orderUpdateReceiver, filter);
    }

    private void initView() {
        // 返回按钮
        ImageView backBtn = findViewById(R.id.back_btn);
        backBtn.setOnClickListener(this);

        // 标题
        TextView titleView = findViewById(R.id.title);
        titleView.setText("我的订单");

        gridView = findViewById(R.id.grid_view);
        emptyLayout = findViewById(R.id.empty_layout);

        gridView = findViewById(R.id.grid_view);
        gridView.setFocusable(true); // 设置 GridView 可获取焦点
        gridView.setFocusableInTouchMode(true);

        dataList = new ArrayList<>();
        adapter = new SimpleAdapter(this, dataList, R.layout.item_order,
                new String[]{"goods_name", "goods_price"},
                new int[]{R.id.tv_goods_name, R.id.tv_goods_price});
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener((parent, view, position, id) -> {
            Log.d("DingDanActivity", "点击事件触发，位置=" + position);
            try {
                int goodsId = (int) dataList.get(position).get("goods_id");
                Log.d("DingDanActivity", "点击商品，ID=" + goodsId);
                Intent intent = new Intent(this, GoodsDetailActivity.class);
                intent.putExtra("goodsId", goodsId);
                startActivity(intent);
            } catch (Exception e) {
                Log.e("DingDanActivity", "点击事件处理出错：" + e.getMessage());
            }
        });
    }

    @SuppressLint("Range")
    private void loadCollectionData() {
        Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.qu_tao.provider/order1"), null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            emptyLayout.setVisibility(View.GONE);
            gridView.setVisibility(View.VISIBLE);

            dataList.clear();
            while (cursor.moveToNext()) {
                Map<String, Object> map = new HashMap<>();
                map.put("order_id", cursor.getInt(cursor.getColumnIndex("order_id")));
                map.put("goods_id", cursor.getInt(cursor.getColumnIndex("goods_id")));
                map.put("goods_name", cursor.getString(cursor.getColumnIndex("goods_name")));
                map.put("goods_price", "¥" + cursor.getDouble(cursor.getColumnIndex("goods_price")));
                dataList.add(map);
            }
            Log.d("DingDanActivity", "数据加载成功，数量: " + dataList.size());
            adapter.notifyDataSetChanged();
            cursor.close();
        } else {
            emptyLayout.setVisibility(View.VISIBLE);
            gridView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back_btn) {
            finish(); // 返回上一页
        }
    }
    public void goShopping(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish(); // 关闭当前页面
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        if (orderUpdateReceiver != null) {
            unregisterReceiver(orderUpdateReceiver);
        }
    }
    public void onCancelOrderClick(View view) {
        try {
            // 获取点击的按钮所在的布局
            LinearLayout parentLayout = (LinearLayout) view.getParent().getParent();
            // 获取订单的位置
            int position = gridView.getPositionForView(parentLayout);
            if (position != AdapterView.INVALID_POSITION) {
                // 获取订单的 order_id
                Object orderIdObj = dataList.get(position).get("order_id");
                if (orderIdObj != null) {
                    int orderId = (int) orderIdObj;
                    // 从数据库中删除该订单
                    int rowsDeleted = getContentResolver().delete(Uri.parse("content://com.example.qu_tao.provider/order1/" + orderId), null, null);
                    if (rowsDeleted > 0) {
                        // 订单删除成功，更新订单列表
                        dataList.remove(position);
                        adapter.notifyDataSetChanged();
                        if (dataList.isEmpty()) {
                            emptyLayout.setVisibility(View.VISIBLE);
                            gridView.setVisibility(View.GONE);
                        }
                    }
                } else {
                    // 处理 order_id 为 null 的情况，例如给出提示信息
                    Toast.makeText(this, "订单 ID 为空，无法取消订单", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "取消订单时出现错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}